package com.apotik.legenda.frameinternal;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import com.apotik.legenda.custom.TableModelCustom;
import com.apotik.legenda.dao.PurchaseDao;
import com.apotik.legenda.dao.PurchaseItemDao;
import com.apotik.legenda.dao.SupplierDao;
import com.apotik.legenda.dialog.AddEditPurchaseDialog;
import com.apotik.legenda.dialog.AddEditPurchaseItemDialog;
import com.apotik.legenda.model.Purchases;
import com.apotik.legenda.model.PurchasesItem;
import com.apotik.legenda.model.Supplier;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.GeneralObserver;
import com.apotik.legenda.util.AppUtil;
import com.apotik.legenda.util.CalendarUtil;

import java.awt.Font;

import javax.swing.border.EmptyBorder;

public class PembelianInternalFrame extends JInternalFrame implements ActionListener, GeneralObserver  {
	private static final long serialVersionUID = 1L;
	
	public static final String OBSERBER_FROM = "FROM";
	public static final String OBSERBER_PURCHASE = "PURCHASE";
	public static final String OBSERBER_PURCHASE_ITEM = "PURCHASE_ITEM";
	
	
	private User user;
	private Purchases currentPurchase;
	private PurchasesItem currentPurchaseItem;
	private int modelRow  = -1;
	private int maxData = 100;
	private int sizePage = 0;
	private int activePageIndex = 0;
	private String[] columnNames = {"No.", "No. Faktur", "Supplier", "Tgl Pembelian"/*, "Dibuat oleh"*/};
	private int modelRow2  = -1;
	private String[] columnNames2 = {"Nama Barang", /*"Kode Barang",*/ "Expire Date", "Isi/Pak", "Harga Satuan", "PPN", "Markup", "Harga Eceran"};
	private List<Supplier> supplierList;
	
	private JTextField textFieldSearch;
	private JLabel lblKetData;
	private TableModelCustom tableModel;
	private TableModelCustom tableModel2;
	private JTable table;
	private JTable table2;
	private AddEditPurchaseDialog addEditPurchaseDialog;
	private AddEditPurchaseItemDialog addEditPurchaseItemDialog;
	
	private JButton btnAdd;
	private JButton btnEdit;
	private JButton btnHapus;
	private JButton btnRefresh;
	private JButton btnBackPage;
	private JButton btnNextPage;
	private JButton btnAddPurchaseItem;
	private JButton btnEditPurchaseItem;
	private JButton btnHapusPurchaseItem;
	private JButton btnRefreshPurchaseItem;
	
	
	@SuppressWarnings("serial")
	public PembelianInternalFrame(User user) {
		super("Pembelian", true, true, true, true);
		
		this.user = user;
		
		setSize(800, 400);
		setVisible(true);
		
		loadSuppliers();
		
		tableModel = new TableModelCustom(columnNames);
		
		JPanel purchasePanel = new JPanel();
		getContentPane().add(purchasePanel, BorderLayout.WEST);
		purchasePanel.setLayout(new BorderLayout(0, 0));
		
		JPanel northPanel = new JPanel();
		purchasePanel.add(northPanel, BorderLayout.NORTH);
		northPanel.setLayout(new BorderLayout());
		
		JPanel headPanel = new JPanel();
		headPanel.setLayout(new BorderLayout());
		northPanel.add(headPanel, BorderLayout.NORTH);
		
		JPanel btns1Panel = new JPanel();
		btns1Panel.setLayout(new FlowLayout());
		headPanel.add(btns1Panel, BorderLayout.WEST);
		
		btnAdd = new JButton("Tambah");
		btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnAdd.addActionListener(this);
		btnAdd.setMnemonic(KeyEvent.VK_N);
		btnAdd.setToolTipText("ALT + N");
		btns1Panel.add(btnAdd);
		
		btnEdit = new JButton("Edit");
		btnEdit.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnEdit.addActionListener(this);
		btns1Panel.add(btnEdit);
		
		btnHapus = new JButton("Hapus");
		btnHapus.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnHapus.addActionListener(this);
		btns1Panel.add(btnHapus);
		
		btnRefresh = new JButton("Refresh");
		btnRefresh.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnRefresh.addActionListener(this);
		btns1Panel.add(btnRefresh);
		
		textFieldSearch = new JTextField();
		textFieldSearch.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
		        if (e.getKeyCode()==KeyEvent.VK_ENTER){
		        	String search = textFieldSearch.getText().trim();
		        	loadDataTablePurchase(0, search);
		        }
			}
			@Override
			public void keyTyped(KeyEvent arg0) {
			}
		});
		headPanel.add(textFieldSearch, BorderLayout.EAST);
		textFieldSearch.setColumns(13);
		
		JLabel lblCari = new JLabel("Cari: ");
		lblCari.setHorizontalAlignment(SwingConstants.RIGHT);
		headPanel.add(lblCari, BorderLayout.CENTER);
		
		JSeparator separator = new JSeparator();
		northPanel.add(separator, BorderLayout.SOUTH);
		
		JPanel panelPurcahse = new JPanel();
		purchasePanel.add(panelPurcahse, BorderLayout.CENTER);
		panelPurcahse.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panelPurcahse.add(scrollPane);
		
		table = new JTable(){
			@Override
			public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
				JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
				
				if(column==0 || column==3){
					label.setHorizontalAlignment(JLabel.CENTER);
				}/*else if(column==7 || column==8){
					label.setHorizontalAlignment(JLabel.RIGHT);
				}*/else{
					label.setHorizontalAlignment(JLabel.LEFT);
				}
				
				return label;
			}
		};
		table.setModel(tableModel);
		table.setEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("rawtypes")
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table.getSelectedRow();
				if(viewRow>-1){
					modelRow = table.convertRowIndexToModel(viewRow);
					Vector v = (Vector) tableModel.getRowVector().get(modelRow);
					if(v!=null){
						currentPurchase = (Purchases) v.get(v.size()-1);
						//System.out.println("currentPurchase: "+(currentPurchase!=null ? currentPurchase.getInvoiceNo():""));
						loadDataTablePurchaseItem();
					}	
				}
			}
		});
		scrollPane.setViewportView(table);
		
		TableColumn column = null;
		column = table.getColumnModel().getColumn(0);
		column.setMaxWidth(50);
		column = table.getColumnModel().getColumn(1);
		column.setPreferredWidth(6);
		column = table.getColumnModel().getColumn(3);
		column.setPreferredWidth(5);
		
		
		JPanel panel_1 = panel1();
		panelPurcahse.add(panel_1, BorderLayout.SOUTH);
		
		loadDataTablePurchase(0, "");
		
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(0, 5, 0, 0));
		getContentPane().add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.NORTH);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_2.add(panel_3, BorderLayout.WEST);
		
		btnAddPurchaseItem = new JButton("Tambah");
		btnAddPurchaseItem.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnAddPurchaseItem.addActionListener(this);
		panel_3.add(btnAddPurchaseItem);
		
		btnEditPurchaseItem = new JButton("Edit");
		btnEditPurchaseItem.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnEditPurchaseItem.addActionListener(this);
		panel_3.add(btnEditPurchaseItem);
		
		btnHapusPurchaseItem = new JButton("Hapus");
		btnHapusPurchaseItem.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnHapusPurchaseItem.addActionListener(this);
		panel_3.add(btnHapusPurchaseItem);
		
		btnRefreshPurchaseItem = new JButton("Refresh");
		btnRefreshPurchaseItem.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnRefreshPurchaseItem.addActionListener(this);
		panel_3.add(btnRefreshPurchaseItem);
		
		/*JLabel lblCariPurchaseItem = new JLabel(" Cari:  ");
		lblCariPurchaseItem.setHorizontalAlignment(SwingConstants.RIGHT);
		panel_2.add(lblCariPurchaseItem, BorderLayout.CENTER);
		
		textField = new JTextField();
		panel_2.add(textField, BorderLayout.EAST);
		textField.setColumns(10);*/
		
		JPanel panel_4 = new JPanel();
		panel.add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane_1 = new JScrollPane();
		panel_4.add(scrollPane_1, BorderLayout.CENTER);
		
		tableModel2 = new TableModelCustom(columnNames2);
		table2 = new JTable(){
			@Override
			public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
				JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
				
				/*if(column==0){
					label.setHorizontalAlignment(JLabel.CENTER);
				}else if(column==7 || column==8){
					label.setHorizontalAlignment(JLabel.RIGHT);
				}else{
					label.setHorizontalAlignment(JLabel.LEFT);
				}*/
				
				return label;
			}
		};
		table2.setModel(tableModel2);
		table2.setEnabled(true);
		table2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table2.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("rawtypes")
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table2.getSelectedRow();
				if(viewRow>-1){
					modelRow2 = table2.convertRowIndexToModel(viewRow);
					Vector v = (Vector) tableModel2.getRowVector().get(modelRow2);
					if(v!=null){
						currentPurchaseItem = (PurchasesItem) v.get(v.size()-1);
						System.out.println("currentPurchaseItem: "+(currentPurchaseItem!=null ? currentPurchaseItem.getPurchasesItemId():""));
					}
				}
			}
		});
		scrollPane_1.setViewportView(table2);
	}
	
	private JPanel panel1(){
		JPanel panel_1 = new JPanel();
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel  panel_2 = new JPanel();
		panel_1.add(panel_2, BorderLayout.EAST);
		
		btnBackPage = new JButton("< Back");
		btnBackPage.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnBackPage.addActionListener(this);
		panel_2.add(btnBackPage);
		
		btnNextPage = new JButton("Next >");
		btnNextPage.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnNextPage.addActionListener(this);
		panel_2.add(btnNextPage);
		
		lblKetData = new JLabel();
		panel_1.add(lblKetData, BorderLayout.WEST);
		
		return panel_1;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void loadDataTablePurchase(int start, String searchValue){
		PurchaseDao dao = new PurchaseDao();
		List<Purchases> list = new ArrayList<>();
		if(searchValue.equalsIgnoreCase("")){
			list = dao.listByAnyCriteria("", start, maxData);
		}else{
			list = dao.listByAnyCriteria(searchValue, start, maxData);
		}
		
		tableModel.removeRowAll();
		if(list!=null){
			if(list.size()>0){
				int i = start+1;
				for(Purchases d: list){
					String noFaktur = "";
					if(d.getInvoiceNo()!=null){
						noFaktur = d.getInvoiceNo();
					}
					
					String supplierName = "";
					if(d.getSupplier()!=null){
						supplierName = d.getSupplier().getSupplierName();
					}
					
					String tglBeli = "";
					if(d.getPurchaseDate()!=null){
						tglBeli = CalendarUtil.formatDate(d.getPurchaseDate(), "dd-MMM-YYYY");
					}
					
					Vector v = new Vector();
					v.add(i);
					v.add(noFaktur);
					v.add(supplierName);
					v.add(tglBeli);
					//v.add(d.getCreatedBy()!=null ? d.getCreatedBy().getFullName():"");
					v.add(d);
					tableModel.insertData(v);
					i++;
				}
				
				int _totalData = totalData();
				if(_totalData<maxData){
					lblKetData.setText("   Data "+(start+1)+" - "+_totalData+" dari "+_totalData);
				}else{
					lblKetData.setText("   Data "+(start+1)+" - "+(start+maxData)+" dari "+_totalData);
				}
			}else{
				lblKetData.setText("   Data 0 dari 0");
			}
		}   
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void loadDataTablePurchaseItem(){
		if(currentPurchase!=null){
			
			PurchaseItemDao dao = new PurchaseItemDao();
			List<PurchasesItem> list = dao.listByPurchase(currentPurchase);
			
			tableModel2.removeRowAll();
			if(list!=null){
				if(list.size()>0){
					for(PurchasesItem o: list){
						String ppn = "";
						if(o.getPpnAmount()!=null){
							ppn = o.getPpnPersen()+"% = "+AppUtil.formatStringIDR(o.getPpnAmount().intValue());
						}
						
						String markup = "";
						if(o.getMarkupAmount()!=null){
							markup = o.getMarkupPersen()+"% = "+AppUtil.formatStringIDR(o.getMarkupAmount().intValue());
						}
						
						String hargaEceran = "";
						if(o.getPriceSell()!=null){
							hargaEceran = AppUtil.formatStringIDR(o.getPriceSell().intValue());
						}
						
						Vector v = new Vector<>();
						v.add(o.getProductName()!=null ? o.getProductName():"");
						//v.add(o.getProductCode()!=null ? o.getProductCode():"");
						v.add(o.getExpireDate()!=null ? CalendarUtil.formatDate(o.getExpireDate(), "dd-MMM-YYYY"):"");
						v.add(Integer.toString(o.getQuantityPerPack()));
						v.add(o.getPriceUnit()!=null ? AppUtil.formatStringIDR(o.getPriceUnit().intValue()):"");
						v.add(" "+ppn);
						v.add(" "+markup);
						v.add(hargaEceran);
						v.add(o);
						tableModel2.insertData(v);
					}
				}
			}
		}
	}
	
	public void loadSuppliers(){
		SupplierDao dao = new SupplierDao();
		List<Supplier> list = dao.listByActive(true, "supplierName");
		this.supplierList = list;
	}
	
	private int totalData(){
		String searchValue = textFieldSearch.getText().trim();
		
		PurchaseDao dao = new PurchaseDao();
		int sizeData = dao.size(searchValue);
		return sizeData;
	}
	
	private String[] paginationValues(){
		int sizeRow = totalData();
		int divide = sizeRow/maxData;
		int mod = sizeRow % maxData;
		sizePage = divide;
		if(mod!=0){
			sizePage = divide + 1;
		}
		
		String[] result = new String[sizePage];
		for(int i=0;i<sizePage;i++){
			result[i] = Integer.toString(i+1);
		}
		return result;
	}
	
	@Override
	public void actionPerformed(ActionEvent ae) {
		Object obj =  ae.getSource();
		
		if(obj==btnAdd){
			boolean isVisible = false;
			if(addEditPurchaseDialog!=null){
				isVisible = addEditPurchaseDialog.isVisible();
			}
			
			if(isVisible){
				addEditPurchaseDialog.toFront();
				addEditPurchaseDialog.requestFocus();
			}else{
				addEditPurchaseDialog = new AddEditPurchaseDialog(this, user, supplierList, activePageIndex, "Tambah" );
				addEditPurchaseDialog.setVisible(true);
				addEditPurchaseDialog.requestFocus();
			}
			
		}else if(obj==btnEdit){
			boolean isVisible = false;
			if(addEditPurchaseDialog!=null){
				isVisible = addEditPurchaseDialog.isVisible();
			}
			
			if(isVisible){
				addEditPurchaseDialog.toFront();
				addEditPurchaseDialog.requestFocus();
			}else{
				addEditPurchaseDialog = new AddEditPurchaseDialog(this, user, supplierList, activePageIndex, "Edit" );
				addEditPurchaseDialog.setVisible(true);
				addEditPurchaseDialog.requestFocus();
			}
			
			addEditPurchaseDialog.editAction(currentPurchase);
			
			
		}else if(obj==btnRefresh){
			loadDataTablePurchase(0, "");
			activePageIndex = 0;
			currentPurchase = null;
			tableModel2.removeRowAll();
			
		}else if(obj==btnBackPage){
			if(activePageIndex!=0){
				int minusOne = activePageIndex-1;
				
				int start = 0;
				String[] paginContent = paginationValues();
				for(int i=0;i<paginContent.length;i++){
					if(i==minusOne){
						start = i*maxData;
					}
				}
				
				activePageIndex = minusOne;
				loadDataTablePurchase(start, textFieldSearch.getText().trim());
			}
			
		}else if(obj==btnNextPage){
			int plusOne = activePageIndex+1;
			if((plusOne)!=sizePage){
				int start = 0;
				String[] paginContent = paginationValues();
				for(int i=0;i<paginContent.length;i++){
					if(i==plusOne){
						start = i*maxData;
					}
				}
				
				activePageIndex = plusOne;
				loadDataTablePurchase(start, textFieldSearch.getText().trim());
				
				/*System.out.println("sizePage: "+sizePage);
				System.out.println("plusOne: "+plusOne);
				System.out.println();*/
				
				int totalData = totalData();
				if(sizePage==(plusOne+1)){
					lblKetData.setText("   Data "+(start+1)+" - "+totalData+" dari "+totalData);
				}else{
					lblKetData.setText("   Data "+(start+1)+" - "+(start+maxData)+" dari "+totalData);
				}
			}
			
		}else if(obj==btnAddPurchaseItem){
			if(currentPurchase!=null ){
				boolean isVisible = false;
				if(addEditPurchaseItemDialog!=null){
					isVisible = addEditPurchaseItemDialog.isVisible();
				}
				
				if(isVisible){
					addEditPurchaseItemDialog.toFront();
					addEditPurchaseItemDialog.requestFocus();
				}else{
					addEditPurchaseItemDialog = new AddEditPurchaseItemDialog("Tambah", currentPurchase, this, user);
					addEditPurchaseItemDialog.setVisible(true);
					addEditPurchaseItemDialog.requestFocus();
				}
			}
		}else if(obj==btnEditPurchaseItem){
			if(currentPurchase!=null ){
				boolean isVisible = false;
				if(addEditPurchaseItemDialog!=null){
					isVisible = addEditPurchaseItemDialog.isVisible();
				}
				
				if(isVisible){
					addEditPurchaseItemDialog.toFront();
					addEditPurchaseItemDialog.requestFocus();
				}else{
					addEditPurchaseItemDialog = new AddEditPurchaseItemDialog("Tambah", currentPurchase, this, user);
					addEditPurchaseItemDialog.setVisible(true);
					addEditPurchaseItemDialog.requestFocus();
				}
			}
		}
	}

	@Override
	public void response(HashMap<String, Object> hm) {
		try {
			String from = (String) hm.get(OBSERBER_FROM);
			
			if(from.equalsIgnoreCase(OBSERBER_PURCHASE)){
				int activePageIndex = (int) hm.get("activePageIndex");
				
				int start = 0;
				if(activePageIndex==-1){//kalo insert
					start = (paginationValues().length-1) * maxData;
				}else{
					start = activePageIndex * maxData;
				}

				loadDataTablePurchase(start, textFieldSearch.getText().trim());
				
			}else if(from.equalsIgnoreCase(OBSERBER_PURCHASE_ITEM)){
				loadDataTablePurchaseItem();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}